﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControlsLib;
using GestionePolveriLib.BL;
using BrightIdeasSoftware;
using GestionePolveriLib.Facades;
using GestionePolveri2.Filters;
using FrameworkLib.Filters;
using GestionePolveri2.DAL;
using GestionePolveriLib.BL.FilterBags;
using FrameworkLib.Utilities.Export;
using FrameworkLib.Configurations.FormsConfiguration;
using FrameworkLib.Configurations.FormsConfiguration.BL;
using FrameworkLib.Utilities;

namespace GestionePolveri2
{
    public partial class VerniciatoreScortaMinima : VerniciatoreScortaMinimaBase
    {
        List<Polvere> m_polveriModificate = null;
        ScortaMinimaFacade pf = null;
        string[] columnsToHide = null;

        public VerniciatoreScortaMinima()
        {
            this.LoadCompleted += new LoadCompletedEventHandler(VerniciatoreScortaMinima_LoadCompleted);

            InitializeComponent();
        }

        public override void InitializeForm()
        {
            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            string[] roles = System.Web.Security.Roles.GetRolesForUser(m_operatore.Identity.Name);

            SavingConfigurationBag scb = new SavingConfigurationBag();
            scb.FormName = this.Name;
            scb.RoleName = roles[0];
            this.SavingConfigurationBag = scb;

            base.InitializeForm();

            this.CanModify = false;
            this.ShowOnlyCustomButton = true;

            this.AddCustomButton("btnSalva", "Salva");
            this.AddCustomButton("btnAllineamento", "Situazione Lotti");

            this.AddCustomButton("btnStampa", "Stampa");
            this.AddCustomButton("btnExport", "Esporta in Excel");

            this.ButtonClicked += new EventHandler<CustomEventArgs<Polvere>>(Anagrafica_ButtonClicked);
            this.CustomButtonClicked += new EventHandler<CustomEventArgs<Polvere>>(Amministrazione2_CustomButtonClicked);

            this.ItemSelected += new EventHandler<CustomEventArgs<Polvere>>(Anagrafica_ItemSelected);

            this.objectListView1.ItemChecked += new ItemCheckedEventHandler(objectListView1_ItemChecked);
            this.objectListView1.CellEditFinishing += new CellEditEventHandler(objectListView1_CellEditFinishing);
            this.objectListView1.FormatRow += new EventHandler<FormatRowEventArgs>(objectListView1_FormatRow);
            this.objectListView1.CellClick += new EventHandler<CellClickEventArgs>(objectListView1_CellClick);

            this.objectListView1.KeyDown += new KeyEventHandler(objectListView1_KeyDown);

            this.contextMenuStrip1.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuStrip1_ItemClicked);
            //
            this.ShowCNFGMenu = true;

            this.InitializeButtonBar();
        }

        void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == standardReportToolStripMenuItem.Name)
            {
                List<ScortaMinimaInfo> result = (List<ScortaMinimaInfo>)this.objectListView1.Objects;

                GestionePolveri2.Reports.ReportViewerDialog2 rpd2 = new GestionePolveri2.Reports.ReportViewerDialog2();
                rpd2.Datasource = result;
                rpd2.Report = "ReportSituazioneMagazzinoAVideo";
                rpd2.ReportViewer.PrinterSettings.DefaultPageSettings.Landscape = true;
                rpd2.ShowReport();
            }

            if (e.ClickedItem.Name == situazioneConLottiToolStripMenuItem.Name)
            {
                LottoFacade pf = new LottoFacade();
                pf.RunAsync(() => pf.GetLottiByPolvereList(), (result) =>
                {
                    if (result != null)
                    {
                        GestionePolveri2.Reports.ReportViewerDialog2 rpd2 = new GestionePolveri2.Reports.ReportViewerDialog2();
                        //rpd2.Datasource = this.dataGridView1.DataSource;
                        rpd2.Datasource = result;
                        rpd2.Report = "ReportSituazioneMagazzino";
                        rpd2.ReportViewer.PrinterSettings.DefaultPageSettings.Landscape = true;
                        rpd2.ShowReport();
                    }
                });
            }
        }

        void objectListView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                if (c != null)  //OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                {
                    AllineamentoInventarioDialog aid = new AllineamentoInventarioDialog();
                    aid.ScortaMinimaInfo = (ScortaMinimaInfo)c.RowObject;
                    if (aid.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {

                    }
                }
            }
        }

        void objectListView1_CellClick(object sender, CellClickEventArgs e)
        {
            //if (e.ClickCount == 2)
            //{
            //    if (e.Item != null)  //OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
            //    {
            //        AllineamentoInventarioDialog aid = new AllineamentoInventarioDialog();
            //        aid.ScortaMinimaInfo = (ScortaMinimaInfo)e.Item.RowObject;
            //        if (aid.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //        {

            //        }
            //    }
            //}
        }

        protected override void OnLoadCompleted()
        {
            base.OnLoadCompleted();

            pf = new ScortaMinimaFacade();

            NascondiColonne();

            InizializzaCampi();

            RefreshColumns();
        }

        void VerniciatoreScortaMinima_LoadCompleted()
        {
            if (!this.DesignMode)
            {
                this.CanModify = false;
                this.ShowOnlyCustomButton = true;

                this.AddCustomButton("btnStampa", "Stampa");
                this.AddCustomButton("btnExport", "Esporta in Excel");

                this.ButtonClicked += new EventHandler<CustomEventArgs<Polvere>>(Anagrafica_ButtonClicked);
                this.CustomButtonClicked += new EventHandler<CustomEventArgs<Polvere>>(Amministrazione2_CustomButtonClicked);

                this.ItemSelected += new EventHandler<CustomEventArgs<Polvere>>(Anagrafica_ItemSelected);

                this.objectListView1.ItemChecked += new ItemCheckedEventHandler(objectListView1_ItemChecked);
                this.objectListView1.CellEditFinishing += new CellEditEventHandler(objectListView1_CellEditFinishing);
                this.objectListView1.FormatRow += new EventHandler<FormatRowEventArgs>(objectListView1_FormatRow);

                this.AddCustomButton("btnSalva", "Salva");

                //
                this.ShowCNFGMenu = true;

                pf = new ScortaMinimaFacade();

                this.InitializeButtonBar();

                NascondiColonne();
                InizializzaCampi();
            }

            RefreshColumns();
        }

        void Anagrafica_ButtonClicked(object sender, CustomEventArgs<Polvere> e)
        {
            switch (e.Action)
            {
                case Actions.New:
                    {
                    }
                    break;
                case Actions.Add:
                    {
                    }
                    break;
                case Actions.Modify:
                    {
                    }
                    break;
                case Actions.Delete:
                    {
                    }
                    break;
                default:
                    break;
            }
        }

        void Anagrafica_ItemSelected(object sender, CustomEventArgs<Polvere> e)
        {
            base.Current = e.Item;
        }

        void objectListView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            Polvere m_polvere = ((Polvere)((OLVListItem)e.Item).RowObject);
        }

        void objectListView1_CellEditFinishing(object sender, CellEditEventArgs e)
        {
            Polvere polvere = (Polvere)e.RowObject;

            m_polveriModificate.Add(polvere);
        }

        void objectListView1_FormatRow(object sender, FormatRowEventArgs e)
        {
            Color m_color = this.objectListView1.BackColor;

            Polvere polvere = (Polvere)e.Model;
            if (polvere.Giacenza < polvere.ScortaMinima)
            {
                m_color = Color.Red;
            }

            this.objectListView1.Items[e.RowIndex].BackColor = m_color;
        }

        void Amministrazione2_CustomButtonClicked(object sender, CustomEventArgs<Polvere> e)
        {
            if (e.ButtonName.Equals("btnAllineamento", StringComparison.InvariantCultureIgnoreCase))
            {
                if (e.Item != null)  //OLVListItem c = (OLVListItem)this.objectListView1.SelectedItem;
                {
                    AllineamentoInventarioDialog aid = new AllineamentoInventarioDialog();
                    aid.ScortaMinimaInfo = (ScortaMinimaInfo)e.Item;
                    if (aid.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {

                    }
                }
                else
                    MessageBox.Show("Selezionare una polvere!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            if (e.ButtonName.Equals("btnExport", StringComparison.InvariantCultureIgnoreCase))
            {
                ScortaMinimaFacade pf = new ScortaMinimaFacade();
                pf.RunAsync(() => GetDataToExport(), (result) =>  //   () => pf.GetMovimenti(), (result) =>
                {
                    if (result != null)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter = "Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
                        sfd.FilterIndex = 1;
                        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string errorMessage = string.Empty;
                            if (((List<ScortaMinimaInfo>)result).ToExcel(sfd.FileName, out errorMessage, columnsToHide))
                            {
                                MessageBox.Show("Esportazione in Excel effettuata!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show(string.Format("ATTENZIONE: Si è verificato un errore: {0}", errorMessage), "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Nessun dato da inviare in stampa.", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                });
            }

            if (e.ButtonName.Equals("btnStampa", StringComparison.InvariantCultureIgnoreCase))
            {
                Button btn = this.ButtonBar.GetCustomButton("btnStampa");
                this.contextMenuStrip1.Show(btn, new Point(0, 0), ToolStripDropDownDirection.AboveRight);


                // stampa usando la funzione della ObjectListView...
                //BrightIdeasSoftware.ListViewPrinter lvp = new ListViewPrinter();
                //lvp.ListView = this.objectListView1;
                //lvp.Header = this.Text;
                //lvp.HeaderFormat.Font = new Font(FontFamily.GenericSerif, 10);
                //lvp.IsShrinkToFit = false;
                //lvp.DefaultPageSettings.Landscape = true;
                //lvp.PrintPreview();

                //LottoFacade pf = new LottoFacade();
                //pf.RunAsync(() => pf.GetLottiByPolvereList(), (result) => 
                //{
                //    if (result != null)
                //    {
                //        GestionePolveri2.Reports.ReportViewerDialog2 rpd2 = new GestionePolveri2.Reports.ReportViewerDialog2();
                //        //rpd2.Datasource = this.dataGridView1.DataSource;
                //        rpd2.Datasource = result;
                //        rpd2.Report = "ReportSituazioneMagazzino";
                //        rpd2.ReportViewer.PrinterSettings.DefaultPageSettings.Landscape = true;
                //        rpd2.ShowReport();
                //    }
                //});
            }

            if (e.ButtonName.Equals("btnSalva", StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    if (m_polveriModificate.Count() > 0)
                    {
                        PolvereFacade pf = new PolvereFacade();

                        pf.Transact(() =>
                        {
                            foreach (Polvere p in m_polveriModificate)
                            {
                                pf.Modify(p);
                            }
                        });

                        MessageBox.Show("Dati salvati correttamente !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Errore durante il salvataggio dei dati: " + ex.Message, "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                base.ClearControls(this.Controls);

                ManageData();
                //LoadData(false);
            }
        }

        private void NascondiColonne()
        {
            //this.objectListView1.AllColumns.Remove(this.olvColumnPrezzo);
            //this.objectListView1.AllColumns.Remove(this.olvColumnValore);
            //this.lblTotValore.Visible = false;

            //OperatorePrincipal m_OperatorePrincipale = (OperatorePrincipal)System.Threading.Thread.CurrentPrincipal;
            //if (m_OperatorePrincipale.IsInRole("Acquisti") || m_OperatorePrincipale.IsInRole("Direzione") || m_OperatorePrincipale.IsInRole("Amministrazione"))
            //{
            //    this.objectListView1.AllColumns.Add(this.olvColumnPrezzo);
            //    this.objectListView1.AllColumns.Add(this.olvColumnValore);

            //    this.lblTotValore.Visible = true;
            //}


            OperatorePrincipal m_OperatorePrincipale = (OperatorePrincipal)System.Threading.Thread.CurrentPrincipal;
            if (m_OperatorePrincipale.IsInRole("Produzione") || m_OperatorePrincipale.IsInRole("Verniciatura"))
            {
                this.objectListView1.AllColumns.Remove(this.olvColumnPrezzo);
                this.objectListView1.AllColumns.Remove(this.olvColumnValore);

                this.lblTotValore.Visible = false;

                this.objectListView1.RebuildColumns();

                columnsToHide = new string[] {
                                 this.olvColumnPrezzo.AspectName,
                                 this.olvColumnValore.AspectName,
                };
            }



            this.objectListView1.RebuildColumns();
        }

        private List<ScortaMinimaInfo> GetDataToExport()
        {
            List<ScortaMinimaInfo> retValue = null;
            
            ScortaMinimaFacade pf = new ScortaMinimaFacade();

            retValue = (this.IsFiltering ? pf.GetScortaMinimaInfo(this.Filter.FilterBag) : pf.GetScortaMinimaInfo());

            return retValue;
        }

        private void InizializzaCampi()
        {
            //this.splitContainer1.Panel2Collapsed = true;
            
            m_polveriModificate = new List<Polvere>();

            this.ShowFilterTracing = true;

            ManageData();
            //LoadData(true);

            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            if (m_operatore.IsInRole("Direzione") || m_operatore.IsInRole("Produzione"))
            {
                this.olvColumnScortaMinima.IsEditable = false;
                this.EnableButton("btnSalva", false);
                //this.objectListView1.RebuildColumns();                
            }
        }

        public override void OnFilterReset()
        {
            base.OnFilterReset();

            this.IsFiltering = false;
            
            ManageData();
            //LoadData(true);
        }

        public override void OnFilterExecuted()
        {
            base.OnFilterExecuted();

            this.IsFiltering = true;

            //pf.GetNumberOfPages(cf2.FilterBag);

            ManageData();
        }

        private void ManageData()
        {
            SuspendLayout1();

            if (!this.IsFiltering)
            {
                LoadData(false);
            }
            else
            {
                LoadData(this.Filter.FilterBag);
            }

            ResumeLayout1();
        }

        private void ResumeLayout1()
        {
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).EndInit();
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
            this.splitContainer1.ResumeLayout(false);
            this.ResumeLayout(false);
        }

        private void SuspendLayout1()
        {
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.objectListView1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.SuspendLayout();
        }

        private void LoadData(bool selectLast)
        {
            pf.RunAsync<List<ScortaMinimaInfo>>(() => pf.GetScortaMinimaInfo(), (result) =>
            {
                this.objectListView1.AddDecoration(new EditingCellBorderDecoration { UseLightbox = true });
                this.objectListView1.SetObjects((List<ScortaMinimaInfo>)result, true);

                CalcolaTotali((List<ScortaMinimaInfo>)result); 
            });
        }

        private void LoadData(FilterBase<AnagPolveri> filter)
        {
            pf.RunAsync<List<ScortaMinimaInfo>>(() => pf.GetScortaMinimaInfo(filter), (result) =>
            {
                if (result != null)
                {
                    this.objectListView1.AddDecoration(new EditingCellBorderDecoration { UseLightbox = true });
                    this.objectListView1.SetObjects((List<ScortaMinimaInfo>)result, true);

                    CalcolaTotali((List<ScortaMinimaInfo>)result);
                }
                else
                {
                    this.objectListView1.Items.Clear();

                    this.ResetButtons();
                    this.ClearControls(this.Controls);

                    this.objectListView1.Items.Clear();
                }
            });
        }

        private void CalcolaTotali(List<ScortaMinimaInfo> result)
        {
            double m_totaleGiacenza = 0;
            double m_totaleValore = 0;
            foreach (ScortaMinimaInfo sci in result)
            {
                m_totaleGiacenza += sci.Giacenza.GetValueOrDefault();
                m_totaleValore += sci.Valore;
            }

            this.lblTotGiacenza.Text = string.Format("Totale Giacenza: {0:N}", m_totaleGiacenza);
            this.lblTotValore.Text = string.Format("Totale Valore: {0:C}", m_totaleValore);
        }

        public override void OnRipristinaConfigurazioneDefaultMaschera()
        {
            base.OnRipristinaConfigurazioneDefaultMaschera();

            NascondiColonne();
        }

        public override void OnSalvaConfigurazioneMaschera()
        {
            base.OnSalvaConfigurazioneMaschera();

            byte[] data = this.objectListView1.SaveState();

            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            string[] roles = System.Web.Security.Roles.GetRolesForUser(m_operatore.Identity.Name);

            SavingConfigurationBag scb = new SavingConfigurationBag();
            scb.FormName = this.Name;
            scb.RoleName = roles[0];
            //scb.UserName = m_operatore.Identity.Name;

            ColumnsConfigurationManager ccm = new ColumnsConfigurationManager();
            ccm.Configuration = scb;
            ccm.State = data;
            ccm.SaveState();
        }

        private void RefreshColumns()
        {
            ColumnsConfigurationManager ccm = new ColumnsConfigurationManager();
            byte[] state = ccm.GetState(this.Name);

            if (state != null)
            {
                bool result = this.objectListView1.RestoreState(state);
            }

            NascondiColonne();
        }
    }

    public class VerniciatoreScortaMinimaBase : AnagraficaManagerFilteredObjectListView<Polvere, VerniciatoreScortaMinimaFilter, VerniciatoreScortaMinimaFilterBag> { }

    //public class VerniciatoreScortaMinimaBase : AnagraficaManagerObjectListView<Polvere> { }
}
